package com.sample.springbatch.job.sample.reader;

import com.sample.springbatch.job.mapper.WrappedJsonLineMapper;
import com.sample.springbatch.model.RepayOrderInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.LineCallbackHandler;
import org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper;
import org.springframework.batch.item.file.mapping.DefaultLineMapper;
import org.springframework.batch.item.file.separator.JsonRecordSeparatorPolicy;
import org.springframework.batch.item.file.transform.DelimitedLineTokenizer;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

/**
 * Flat文件格式读取类  实现了分隔符和json格式
 * Created by zwg on 2017/8/8.
 */
@Component
public class RepayOrderFlatFileItemReader<T> extends FlatFileItemReader {

    Logger logger = LoggerFactory.getLogger(RepayOrderFlatFileItemReader.class);

    public RepayOrderFlatFileItemReader() {
        //System.out.println(" ====================== times ========="+times);
        repayOrderOfDelimitedLine();
    }


    /**
     * 分隔符文件读取配置
     */
    private void repayOrderOfDelimitedLine() {
        setResource(new ClassPathResource("jobdata/repay-orders-big.dat")); //"jobdata/repay-orders.dat")); //jobdata/repay-orders-big.dat
        setLineMapper(new DefaultLineMapper<RepayOrderInfo>() {{
            setLineTokenizer(new DelimitedLineTokenizer("|") {{  //一行内容分割默认用','分割
                setNames(new String[] { "userId", "productId","contractNo","amount","repayType","repayMethod" });
                setComments(new String[] { "==","##" });  //# 为默认的注释符号
                //setLinesToSkip(1);
            }});
            setFieldSetMapper(new BeanWrapperFieldSetMapper<RepayOrderInfo>() {{
                setTargetType(RepayOrderInfo.class);
            }});
            setSkippedLinesCallback(new LineCallbackHandler() {
                @Override
                public void handleLine(String s) {
                    logger.error("skip line:"+s);
                }
            });

        }});
    }

    /**
     * json文件读取配置
     */
    private void repayOrderOfJsonLine() {
        setResource(new ClassPathResource("jobdata/repay-orders.json"));
        //配置文件中的注释行
        setComments(new String[] { "/*" });
        //配置Json行分割
        setRecordSeparatorPolicy(new JsonRecordSeparatorPolicy());
        //重写JsonLineMapper 直接转成需要的对象结构
        setLineMapper(new WrappedJsonLineMapper<RepayOrderInfo>(RepayOrderInfo.class));
    }
}
